package com.wyix.interceptor;

import com.wyix.exception.AuthException;
import com.wyix.properties.AuthProperties;
import com.wyix.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 权限认证拦截器，用于拦截请求并进行权限验证
 */
public class AuthInterceptor implements HandlerInterceptor {
    private final AuthService authService;
    private final AuthProperties authProperties;

    public AuthInterceptor(AuthService authService, AuthProperties authProperties) {
        this.authService = authService;
        this.authProperties = authProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果权限认证未启用，直接放行
        if (!authProperties.isEnabled()) {
            return true;
        }

        // 从请求头中获取Token
        String token = request.getHeader("Authorization");

        // 检查Token是否存在
        if (token == null || token.isEmpty()) {
            throw new AuthException(401, "未提供Authorization令牌");
        }

        // 检查Token格式，是否以Bearer开头
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 验证Token
        if (!authService.verifyToken(token)) {
            throw new AuthException(401, "无效的令牌或令牌已过期");
        }

        // 将用户名存入请求属性中，方便后续使用
        String username = authService.getUsernameFromToken(token);
        request.setAttribute("currentUser", username);

        // 验证通过，放行
        return true;
    }
}
